//
//  OrderGoodsDetailController.m
//  ios-supplier
//
//  Created by Benlai on 15/8/26.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "OrderGoodsDetailController.h"
#import "OrderDetailFooterView.h"
#import "submitOrderCell1.h"
#import "SubmitOrderCell2.h"
#import "SubmitOrderCell3.h"
#import "SubmitOrder4.h"
#import "SubmitOrderCell5.h"
#import "OrderGoodsController.h"
#import "JFBOrderProductDS.h"
#import "GoodsInStorageController.h"
#import "HistoricalOrderController.h"
#import "ApiConfirmInStorage.h"
@interface OrderGoodsDetailController ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *allProcuctCountLabel;

@property (weak, nonatomic) IBOutlet UIButton *inStorageBtn;

- (IBAction)inStorageBtnPressed:(id)sender;

@property (nonatomic, strong)UITableView *orderInfoTable;

@property (nonatomic, strong)NSArray *orderInfoArray;

//@property(nonatomic, strong)UIImageView *distributionImageView;
@end

@implementation OrderGoodsDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setAutomaticallyAdjustsScrollViewInsets: NO];
    
    self.orderInfoArray = self.orderDetailInfo.shopSOItem;

    self.orderInfoTable = [[UITableView alloc]initWithFrame: CGRectMake(0, TopSizeFix-20, self.view.frame.size.width, self.view.frame.size.height - TopSizeFix - 49) style:UITableViewStyleGrouped];
    self.orderInfoTable.delegate = self;
    self.orderInfoTable.dataSource = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self.orderInfoTable setSeparatorStyle: UITableViewCellSeparatorStyleNone];
    [self.orderInfoTable setSectionHeaderHeight: 0];
    [self.orderInfoTable setShowsVerticalScrollIndicator: NO];
    
    self.orderInfoTable.sectionFooterHeight = 0;
    self.orderInfoTable.sectionHeaderHeight = 0;
    
    [self.view addSubview: self.orderInfoTable];
    
    
    self.totalPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", [self.orderDetailInfo.purchasePrice floatValue]];

//    NSInteger count = 0;
//    for (JFBSubmitOrderDS *goodsInfo in self.orderDetailInfo.shopSOItem)
//    {
//        count += goodsInfo.purchaseUnits;
//    }
//
//    self.allProcuctCountLabel.text = [NSString stringWithFormat: @"(共%ld件)", (long)count];

    self.inStorageBtn.hidden = self.orderDetailInfo.purchaseStatus == 4 ? NO : YES;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
    
}

- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    for (UITableViewController *controller in self.navigationController.viewControllers) {

        if ([controller isKindOfClass:[HistoricalOrderController class]])
        {
            [self.navigationController popToViewController:controller animated:YES];
            return;
        }
    }
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1]  animated:YES];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
{
    for (UITableViewController *controller in self.navigationController.viewControllers) {
        
        if ([controller isKindOfClass:[HistoricalOrderController class]])
        {
            [self.navigationController popToViewController:controller animated:YES];
            return NO;
        }
    }
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1]  animated:YES];
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section != 3) {
        return 1;
    }
    return self.orderInfoArray.count + 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }
    if (indexPath.section == 3 && indexPath.row == self.orderInfoArray.count + 1)
    {
        return 60;
    }
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        return 60;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        if (self.orderDetailInfo.purchaseStatus == 3 || self.orderDetailInfo.purchaseStatus == 4 || self.orderDetailInfo.purchaseStatus == 5)
        {
            return 95;
        }
        else
        {
            return 0;
        }
    }
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *headerView = [[UIView alloc]initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 100)];
        UIImageView *distributionImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 4, 0, self.view.frame.size.width / 2 + 100, 40)];
        
        distributionImageView.center = headerView.center;
        [distributionImageView setContentMode: UIViewContentModeScaleAspectFill];
        
        if (self.orderDetailInfo)
        {
            if (self.orderDetailInfo.purchaseStatus == 3)
            {
                [distributionImageView setImage: [UIImage imageNamed: @"sendBefor"]];
            }
            else if (self.orderDetailInfo.purchaseStatus == 4)
            {
                [distributionImageView setImage: [UIImage imageNamed: @"sendBegin"]];
            }
            else if (self.orderDetailInfo.purchaseStatus == 5)
            {
                [distributionImageView setImage: [UIImage imageNamed: @"sendEnd"]];
            }
        }
        
        [headerView addSubview: distributionImageView];
        return headerView;
    }
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 3)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"OrderDetailFooterView" owner: nil options: nil];
        OrderDetailFooterView *footerView = [arr objectAtIndex: 0];
        if (self.orderDetailInfo) {
            footerView.orderNumber.text = self.orderDetailInfo.purchaseNoInside;
            footerView.orderTime.text = self.orderDetailInfo.createTime;
        }
        return footerView;
    }
    
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    if(indexPath.section == 0)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"submitOrderCell1"owner: nil options: nil];
        cell = [arr objectAtIndex: 0];
        
        submitOrderCell1 *storeInfoCell = (submitOrderCell1*) cell;
        [storeInfoCell setAccessoryType: UITableViewCellAccessoryNone];
        storeInfoCell.storeNameLabel.text = [NSString stringWithFormat: @"%@(%@)",[UserInfo currentUser].shopkeeper,[UserInfo currentUser].contactMobile];
        storeInfoCell.storeAddressLabel.text = [UserInfo currentUser].contactAddr;
//        if (self.orderDetailInfo.receive_name != nil && ![self.orderDetailInfo.receive_name isEqualToString:@""]) {
//            storeInfoCell.storeNameLabel.text = [NSString stringWithFormat: @"%@",self.orderDetailInfo.receive_name];
//        }
//        if (self.orderDetailInfo.receive_phone != nil && ![self.orderDetailInfo.receive_phone isEqualToString:@""]) {
//            storeInfoCell.storeNameLabel.text = [NSString stringWithFormat: @"%@(%@)",self.orderDetailInfo.receive_name,self.orderDetailInfo.receive_phone];
//        }
//        if (self.orderDetailInfo.receive_address != nil && ![self.orderDetailInfo.receive_address isEqualToString:@""]) {
//            storeInfoCell.storeAddressLabel.text = self.orderDetailInfo.receive_address;
//        }
    }
    else if (indexPath.section == 1)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell2"
                                                     owner: nil
                                                   options: nil];
        cell = [arr objectAtIndex: 0];
        
    }
    else if (indexPath.section == 2)
    {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell2"
                                                     owner: nil
                                                   options: nil];
        cell = [arr objectAtIndex: 0];
        
        SubmitOrderCell2 * remarkCell = (SubmitOrderCell2 *)cell;
        remarkCell.leftNameLabel.text = @"备注";
        remarkCell.rightNameLabel.text = self.orderDetailInfo.note;
    }
    else if (indexPath.section == 3)
    {
        
        if (indexPath.row == 0)
        {
            NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell3" owner: nil options: nil];
            cell = [arr objectAtIndex: 0];
            
            SubmitOrderCell3 *cellListTitle = (SubmitOrderCell3 *)cell;
            cellListTitle.goodsNameLabel.text = @"费用清单";
        }
        else if (indexPath.row == self.orderDetailInfo.shopSOItem.count + 1)
        {
            NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrder4" owner: nil options: nil];
            cell = [arr objectAtIndex: 0];
            
            SubmitOrder4 *priceCell = (SubmitOrder4 *)cell;
            
            priceCell.totalPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", [self.orderDetailInfo.purchasePrice floatValue]];
            priceCell.carriagePriceLabel.text = @"￥0.0";
        }
        else
        {
            static NSString *identifier = @"submitOrderCell3";
            cell = [tableView dequeueReusableCellWithIdentifier: identifier];
            
            if (!cell)
            {
                NSArray *arr = [[NSBundle mainBundle] loadNibNamed: @"SubmitOrderCell3" owner: nil options: nil];
                cell = [arr objectAtIndex: 0];
            }
            
            SubmitOrderCell3 *orderCell = (SubmitOrderCell3 *)cell;
            JFBOrderProductDS *orderInfo = self.orderInfoArray[indexPath.row - 1];
            
            orderCell.goodsNameLabel.text = orderInfo.productName;
            orderCell.goodsNumberLabel.text = [NSString stringWithFormat: @"X%ld", (unsigned long)orderInfo.purchaseCount];
            orderCell.goodsPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", [orderInfo.productPrice floatValue]];
        }
    }
    
    [cell setSelectionStyle: UITableViewCellSelectionStyleNone];
    return cell;
}


- (IBAction)inStorageBtnPressed:(id)sender
{
    [JFBUIAnimation alertSure: @"确认入库数量准确无误吗？" delegate: self];
//    GoodsInStorageController *inStorageC = [[GoodsInStorageController alloc] init];
//    inStorageC.goodsData = self.orderDetailInfo.shopSOItem;
//    inStorageC.orderID = self.orderDetailInfo.ID;
//    [self.navigationController pushViewController: inStorageC animated: YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [[[ApiConfirmInStorage alloc]initWithUt:[UserInfo currentUser].ut andWithPurchaseId:self.orderDetailInfo.ID andWithDealPersonId:[[UserInfo currentUser].merchantID integerValue] andWithDealPersonName:[UserInfo currentUser].shopkeeper]startWithCompletionSuccess:^(id JSON, YTKBaseRequest *request) {
            NSLog(@"%@",JSON);
            if ([JSON[@"code"] integerValue] == 0) {
                [JFBUIAnimation alertTips: @"入库成功，库存已更新"];
                [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: 1] animated: YES];
            }else if ([JSON[@"code"] integerValue] == 99){
                UIViewController* viewController;
                UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
    }
}
@end
